package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            queryBlogUser(blog);
            //判断用户是否点过赞
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        // 查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("探店博文不存在");
        }
        // 查询用户
        queryBlogUser(blog);
        //判断用户是否点过赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    private void isBlogLiked(Blog blog){
        //获取用户对象
        UserDTO user = UserHolder.getUser();
        if(user==null){
            //用户未登录，无需获取id
            return;
        }
        Long userId = user.getId();
        //判断用户是否点过赞
        String key=RedisConstants.BLOG_LIKED_KEY + blog.getId();
        Boolean isMember = stringRedisTemplate.opsForZSet().score(key,userId.toString()) != null;
        //设置blog的isLike属性
        blog.setIsLike(isMember);
    }

    @Override
    public Result likeBlog(Long id) {
        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.判断用户是否点过赞
        String key=RedisConstants.BLOG_LIKED_KEY + id;
        Boolean isMember = stringRedisTemplate.opsForZSet().score(key,userId.toString()) != null;
        if(BooleanUtil.isFalse(isMember))
        {
            //2.1如果没有点过赞，执行点赞操作
            //2.2.点赞数量加一
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            //2.3.保存用户到redis集合
            if(isSuccess)
            {
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
            return Result.ok();
        }
        else{
            //3.如果点过赞，取消点赞操作
            //3.1点赞数量减一
            boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            //3.2.从redis集合中移除用户
            if(isSuccess)
            {
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
            return Result.ok();
        }
    }

    @Override
    public Result queryBlogLikes(Long id) {
        //1.查询点赞top5用户
        String key=RedisConstants.BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        //如果没有点赞用户，返回空集合
        if(top5==null || top5.isEmpty())
        {
            return Result.ok(Collections.emptyList());
        }
        //2.解析用户Id
        List<Long> Ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr= StrUtil.join(",",Ids);
        //3.根据用户Id查询用户信息
        //下面一行等价于 select * from tb_user where id in (id1,id2,id3) order by field(id,id1,id2,id3)
        List<User> users = userService.query().in("id",Ids).last("order by field(id,"+idStr+")").list();
        //4.转换为UserDTO
        List<UserDTO> userDTOS = users
                .stream().
                map(user -> BeanUtil.copyProperties(user,UserDTO.class)).
                collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        // 保存探店博文
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("保存失败");
        }
        //查询笔记作者的所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id",userId).list();
        //推送笔记id到笔记作者的粉丝列表
        for (Follow follow : follows) {
            Long followUserId = follow.getUserId();
            String key=RedisConstants.FEED_KEY+followUserId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogByFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱 ZrangeByScore key min max withscores offset count
        String key=RedisConstants.FEED_KEY+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset,3);
        //3.非空判断
        if(typedTuples==null || typedTuples.isEmpty()){
            return Result.ok(Collections.emptyList());
        }
        //4.解析数据
        List<Long> ids = new ArrayList<>();
        long minTime = 0;
        int os=1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //4.1.获取id
            String blogIdStr = tuple.getValue();
            ids.add(Long.valueOf(blogIdStr));
            //4.2.获取分数-时间戳
            long time= tuple.getScore().longValue();
            if(time==minTime){
                os++;
            }else{
                os=1;
            }
            minTime=time;
        }
        //5.根据id查询blog
        List<Blog> blogs = query().in("id",ids).last("order by field(id,"+StrUtil.join(",",ids)+")").list();
        for(Blog blog:blogs){
            queryBlogUser(blog);
            isBlogLiked(blog);
        }
        //6.返回结果
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}
